import {postAction} from "@/request/base";
import passwordUtils from "@/utils/PasswordUtils";
import {defineComponent, h, PropType} from "vue";
import {Picker, PickerOption, Popup} from "vant";
import {PickerColumn} from "vant/lib/picker/types";
import {showComponentToBody} from "@/utils/ComponentUtils";
import {isEmpty} from "@/utils";
import {$notify} from "@hhd/plat/Dialog";
import {$loading} from "@plat";
import store from "@/store";

function encryptUserModel(userModel: any) {
  userModel.password = passwordUtils.encrypt(userModel.username, userModel.password)
  userModel.forceLogin = '0';
  userModel.tenantId = '';
  userModel.remember_me = true;
  userModel.thirdPlatform = 'Local';
}

function saveStorave(res: any) {
  store.commit('user/setToken', res.result.token)
  res.result.userInfo.token = res.result.token;
  store.commit('user/setUserInfo', res.result.userInfo)
}

function loginSuccess(callback: any, res: any) {
  saveStorave(res);
  callback.success(res.result.token);
}

function onLoginResponse(res: any, userModel: any, callback: any) {
  if (!res.success
      && res?.result?.onLine + '' !== '1') {
    $notify({
      title: "登录失败",
      message: res.message,
      type: 'error'
    })
    callback.error(res)
    return;
  }
  //需要选择单位
  if (!isEmpty(res?.result?.multipleUser)) {
    showComponentToBody(h(departSelector, {
      callback,
      userModel,
      columns: resolveMultiUser(res)
    }));
    return;
  }
  //需要确认
  if (res?.result?.onLine + '' === '1') {
    confirmForceLogin(userModel, callback)
    return;
  }
  loginSuccess(callback, res);
}

function confirmForceLogin(userModel: any, callback: any) {
  $notify({
    title: '提示',
    message: '当前账号已登录,是否强制登录？',
    type: 'confirm',
    confirm() {
      userModel.forceLogin = '1';
      doLogin(userModel, callback);
    },
    cancel() {
      callback.error()
    }
  })
}

function doLogin(userModel: any, callback: any) {
  $loading.startLoading();
  postAction('/sys/login', userModel, {
    'X-Tenant-Id': 'master'
  }).then(res => {
    $loading.stopLoading();
    console.log(res)
    onLoginResponse(res, userModel, callback);
  }).catch(err => {
    $loading.stopLoading();
    callback.error(err)
  });
}

export const loginAction = (userModel: any) => {
  encryptUserModel(userModel);

  return new Promise((success, error) => {
    doLogin(userModel, {success, error});
  });
};

function resolveMultiUser(res: any) {
  res.result.multipleUser.forEach((e: any) => {
    e.value = e.tenantId
    e.text = e.tenantId_dictText
  })
  return res.result.multipleUser
}

const departSelector = defineComponent({
  name: 'DepartSelector',
  props: {
    userModel: {
      type: Object,
      default: () => ({})
    },
    callback: {
      type: Object,
      default: () => {
        return {
          success() {
          },
          error() {
          },
        }
      }
    },
    columns: {
      type: Array as PropType<(PickerColumn | PickerOption)[]>,
      default: () => [],
    }
  },
  data() {
    return {
      show: true,
    }
  },
  render() {
    return h(Popup, {
      show: this.show,
      position: 'bottom'
    }, () => [
      h(Picker, {
        columns: this.columns,
        // @ts-ignore
        onConfirm: (...args: any) => this.confirm(...args),
        // @ts-ignore
        onCancel: (...args: any) => this.cancel(...args)
      })
    ])
  },
  methods: {
    cancel(args: any[]) {
      this.$nextTick(() => {
        this.callback.error()
        this.$emit('close')
      })
    },
    // @ts-ignore
    confirm({selectedIndexes, selectedOptions, selectedValues}) {
      this.userModel.tenantId = selectedValues[0];
      doLogin(this.userModel, this.callback);
      this.$emit('close')
    },
  }
})